package com.woyou.ui.activity.orderdetail;

import java.math.BigDecimal;
import java.util.List;

import retrofit.RetrofitError;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.umeng.socialize.controller.UMSocialService;
import com.woyou.bean.Gift;
import com.woyou.bean.Info;
import com.woyou.bean.MyOrderItem;
import com.woyou.bean.OrderDetail;
import com.woyou.bean.OrderGoodsItem;
import com.woyou.bean.OrderOptionItem;
import com.woyou.bean.OrderSubGoodsItem;
import com.woyou.bean.Result;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.OrderDefaultReq;
import com.woyou.service.NetWorkCenter;
import com.woyou.service.receiver.JPushReceiver_;
import com.woyou.ui.activity.BaseActivity;
import com.woyou.ui.activity.HomeActivity_;
import com.woyou.ui.activity.LoginActivity_;
import com.woyou.ui.activity.orderlist.MyOrderActivity;
import com.woyou.ui.api.Command;
import com.woyou.ui.api.RefreshOrderDetailsListener;
import com.woyou.ui.component.ErrorHintView;
import com.woyou.ui.component.SuperUI;
import com.woyou.ui.fragment.AssessmentOrderLayout;
import com.woyou.ui.fragment.CancelOrderLayout;
import com.woyou.ui.fragment.ConReceivTimeOrder;
import com.woyou.ui.fragment.IndexFragment_;
import com.woyou.utils.LogUtil;
import com.woyou.utils.ParseUtils;

/**
 * 订单详情碎片
 * 
 * @author shenzhou 2015年1月14日
 */
public class OrderDetailActivity extends BaseActivity implements ViewControl {

	private static final String TAG = "OrderDetailActivity";

	/** 订单明细 **/
	private LinearLayout orderdetailsLayout;
	/** 配送信息 **/
	private LinearLayout orderinfoLayout;
	/** 确认接单时间 **/
	private ConReceivTimeOrder conReceivTimeOrder;
	/** 取消订单 **/
	private CancelOrderLayout cancelLayout;
	/** 评价订单 **/
	private AssessmentOrderLayout assessmentLayout;

	private RelativeLayout backRight; // 右边的返回键
	private TextView shopName; // 右边返回按钮的店铺名称

	private OrderDefaultReq orderDefaultReq = new OrderDefaultReq();
	private UserInfo info; // 用户信息

	public FrameLayout mContainer; // 存放view的容器
	public ErrorHintView mErrorHintView;
	public PullToRefreshScrollView mScrollView;
	public UMSocialService mController;

	public TextView downTimeText;
	private RelativeLayout downTimeLinear;

	public OrderDetail mOrderDetail;
	public String oId; // 订单编号
	public String oriClassName; // 从哪个界面进入订单详情的

	private OrderDetailActController mActController;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fm_orderdetail);

		info = mUserModel.getUserInfo();
		registeBroadcast();
		initTitleView();
		initEvent();

		mActController = new OrderDetailActController(mContext, this);
		mActController.loading();
		getData();
	}

	@SuppressWarnings("rawtypes")
	private void getData() {
		if (hasInfo()) {
			Class originClzz = mInfo.getOriginClzz();
			Object object = mInfo.getData();

			if (originClzz != null) {
				oriClassName = originClzz.getName();
			}
			if (object != null && object instanceof MyOrderItem) {
				MyOrderItem order = (MyOrderItem) object;
				oId = order.getoId();
				if (!TextUtils.isEmpty(order.getInfo())) {
					showDialog(order.getInfo());
					if (mController != null) {
						// 隐藏分享面板
						mController.dismissShareBoard();
						// TODO
					}
					dismissDialog();
				}
			} else if (object != null && object instanceof String) {
				oId = (String) object;
			}
			loadOrderDetail(oId);
		}
	}

	/** 初始化标题栏 */
	private void initTitleView() {
		mContainer = (FrameLayout) findViewById(R.id.container_fl);
		mErrorHintView = (ErrorHintView) findViewById(R.id.hintView);
		cancelLayout = (CancelOrderLayout) findViewById(R.id.cancel_order);
		conReceivTimeOrder = (ConReceivTimeOrder) findViewById(R.id.confirm_order);
		assessmentLayout = (AssessmentOrderLayout) findViewById(R.id.assessment_order);

		RelativeLayout backLeft = (RelativeLayout) findViewById(R.id.back_left); // 左边的返回按钮
		backRight = (RelativeLayout) findViewById(R.id.back_right); // 右边的返回按钮
		shopName = (TextView) findViewById(R.id.head_shopname);
		backLeft.setOnClickListener(this);
		backRight.setOnClickListener(this);

	}

	private void inflateView() {
		if (mContainer != null)
			mContainer.removeAllViews();

		View view = View.inflate(mContext, R.layout.activity_oderdetail_data, null);
		orderdetailsLayout = (LinearLayout) view.findViewById(R.id.details);
		orderinfoLayout = (LinearLayout) view.findViewById(R.id.deliverinfo);
		mScrollView = (PullToRefreshScrollView) view.findViewById(R.id.scroll);
		downTimeText = (TextView) view.findViewById(R.id.pay_time);
		downTimeLinear = (RelativeLayout) view.findViewById(R.id.countdown_time);

		// 根据状态来显示是否倒计时
		changeUIByState();

		setUpScrollerView();
		// 加载配送信息
		infalaterDeliverInfo(mOrderDetail);
		// 加载订单明细
		infalaterOrderDetails(mOrderDetail);
		// 显示订单状态
		showOrderState(view, mOrderDetail);

		mContainer.addView(view);

	}

	private void changeUIByState() {
		if (mOrderDetail != null) {
			backRight.setVisibility(View.VISIBLE);
			shopName.setText(mOrderDetail.getsName()); // 店铺名称
		} else {
			backRight.setVisibility(View.GONE);
			return;
		}
		if (mOrderDetail.getState() == State.NEW_ORDER_ONLINEPAY) {
			downTimeLinear.setVisibility(View.VISIBLE);
			mActController.startCountDown(mOrderDetail);
		} else {
			downTimeLinear.setVisibility(View.GONE);
		}
	}

	/** 配置scrollView参数 */
	private void setUpScrollerView() {
		mScrollView.setMode(Mode.PULL_FROM_START); // 刷新模式
		mScrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				if (refreshView.isHeaderShown()) {
					loadOrderDetail(oId);
				}
			}
		});

	}

	/**
	 * 加载订单详情
	 * 
	 * @param oId
	 */
	public void loadOrderDetail(final String oId) {
		if (!NetWorkCenter.isNetworkConnected(getContext())) {
			mScrollView.onRefreshComplete();
			mActController.networkError();
			return;
		}

		executeTask(new Runnable() {

			@Override
			public void run() {
				try {
					if (info != null && !info.getuId().equals("")) {
						orderDefaultReq.setoId(oId);
						orderDefaultReq.setuId(info.getuId());
						orderDefaultReq.setPwd(info.getPwd());
						final Result<OrderDetail> result = mOrderModel.v2_3queryOrderDetail(orderDefaultReq);
						runOnUI(new Runnable() {

							@Override
							public void run() {
								if (result != null && result.getCode() == 1) {
									mOrderDetail = result.getData();
									inflateView();
									mActController.showContent();

								} else if (result != null
										&& result.getCode() == -3) {
									mErrorHintView.hideLoading();
									showToast(result.getMsg());
									openActivity(LoginActivity_.class, null);
									finish();

								} else {
									if (oriClassName.equals(JPushReceiver_.class.getName())) {
										mActController.noData();
									} else {
										mActController.loadFailure();
									}
								}
							}
						});
					} else {
						runOnUI(new Runnable() {

							@Override
							public void run() {
								showToast("登录后方可查看订单详情");
								openActivity(LoginActivity_.class, mInfo);
								finish();

							}
						});
					}
				} catch (RetrofitError e) {
					mActController.handleError(e);
				} finally {
					runOnUI(new Runnable() {
						public void run() {
							if (mScrollView != null) {
								mScrollView.onRefreshComplete();
							}
						}
					});
				}
			}
		});
	}

	/** 订单状态 */
	private void showOrderState(View view, OrderDetail orderDetail) {
		TextView oIdText = (TextView) view.findViewById(R.id.noanswer_oid);
		TextView stateText = (TextView) view.findViewById(R.id.noanswer_status);
		oIdText.setText(mOrderDetail.getoId());
		mActController.fillOrderState(orderDetail.getState(), stateText);
		TimeLineLayout timeLineLayout = (TimeLineLayout) view
				.findViewById(R.id.timeLineLayout);
		timeLineLayout.setAdapter(new OrderDetailAdapter(getContext(), this,
				orderDetail) {

		});

	}

	private void initEvent() {
		if (assessmentLayout != null) {
			assessmentLayout.setListener(new RefreshOrderDetailsListener() {
				@Override
				public void callBack(String orderId) {
					oId = orderId;
					mActController.loading();
					loadOrderDetail(oId);
				}
			});
		}

		if (conReceivTimeOrder != null) {
			conReceivTimeOrder.setListener(new RefreshOrderDetailsListener() {
				@Override
				public void callBack(String orderId) {
					oId = orderId;
					mActController.loading();
					loadOrderDetail(oId);
				}
			});
		}

		if (cancelLayout != null) {
			cancelLayout.setListener(new RefreshOrderDetailsListener() {
				@Override
				public void callBack(String orderId) {
					LogUtil.d(TAG, "取消订单");
					oId = orderId;
					mActController.loading();
					loadOrderDetail(oId);
				}
			});
		}

	}

	/**
	 * 加载订单明细
	 */
	LinearLayout orderList;

	private void infalaterOrderDetails(OrderDetail orderDetail) {
		RelativeLayout deliverFeeRela = (RelativeLayout) orderdetailsLayout
				.findViewById(R.id.contents_deliverFee_rela);
		TextView deliverFee = (TextView) orderdetailsLayout
				.findViewById(R.id.contents_deliverFee);
		RelativeLayout mealsBoxSumRela = (RelativeLayout) orderdetailsLayout
				.findViewById(R.id.contents_mealsBoxSum_rela);
		TextView mealsBoxSum = (TextView) orderdetailsLayout
				.findViewById(R.id.contents_mealsBoxSum);
		orderList = (LinearLayout) orderdetailsLayout
				.findViewById(R.id.contents_ll);
		RelativeLayout pCouponRela = (RelativeLayout) orderdetailsLayout
				.findViewById(R.id.contents_pCoupon_rela);
		TextView pCoupon = (TextView) orderdetailsLayout
				.findViewById(R.id.contents_pCoupon);
		RelativeLayout sCouponla = (RelativeLayout) orderdetailsLayout
				.findViewById(R.id.contents_sCoupon_rela);
		TextView sCoupon = (TextView) orderdetailsLayout
				.findViewById(R.id.contents_sCoupon);
		TextView allprices = (TextView) orderdetailsLayout
				.findViewById(R.id.contents_allprices);
		TextView againOrder = (TextView) orderdetailsLayout
				.findViewById(R.id.contents_again); // 再来一单
		TextView shareorder = (TextView) orderdetailsLayout
				.findViewById(R.id.contents_shareorder); // 分享订单
		againOrder.setOnClickListener(this);
		shareorder.setOnClickListener(this);

		String fee = orderDetail.getDeliverFee(); // 配送费
		if (!TextUtils.isEmpty(fee)
				&& !ParseUtils.subZeroAndDot(fee).equals("0")) {
			deliverFee.setText(Html.fromHtml("￥<big>"
					+ ParseUtils.subZeroAndDot(fee) + "</big>"));
		} else {
			deliverFeeRela.setVisibility(View.GONE);
		}
		
		String boxSum = orderDetail.getMealsBoxSum(); // 餐盒费
		if (!TextUtils.isEmpty(boxSum)
				&& !ParseUtils.subZeroAndDot(boxSum).equals("0")) {
			BigDecimal bigDecimal = new BigDecimal(boxSum);
			double d = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			mealsBoxSum.setText(Html.fromHtml("￥<big>"
					+ d + "</big>"));
		} else {
			mealsBoxSumRela.setVisibility(View.GONE);
		}

		// LinearLayout
		List<OrderGoodsItem> goodsList = orderDetail.getGoodsList();
		List<Gift> actyList = orderDetail.getActyList();
		if (actyList != null && actyList.size() > 0) {
			int size = actyList.size();
			for (int i = 0; i < size; i++) {
				Gift gift = actyList.get(i);
				OrderGoodsItem item = new OrderGoodsItem();
				item.setgName(gift.getaName());
				item.setPrice(gift.getPrice());
				item.setQty(gift.getQty());
				goodsList.add(item);
			}
		}

		if (goodsList != null && goodsList.size() > 0) {
			int size = goodsList.size();
			for (int i = 0; i < size; i++) {
				OrderGoodsItem goodsItem = goodsList.get(i);
				View itemView = View.inflate(mContext,
						R.layout.item_orderdetail_lv, null);
				TextView goodName = (TextView) itemView.findViewById(R.id.name);
				TextView goodNum = (TextView) itemView.findViewById(R.id.num);
				TextView goodPrice = (TextView) itemView
						.findViewById(R.id.price);
				TextView goodOption = (TextView) itemView
						.findViewById(R.id.option);

				goodName.setText(goodsItem.getgName());
				goodNum.setText("x" + goodsItem.getQty() + "");

				String money = ParseUtils.String2Money(goodsItem.getPrice());
				int indexOf = money.indexOf("-");
				if (indexOf == -1) {
					goodPrice.setTextColor(Color.BLACK);
				} else {
					goodPrice.setTextColor(Color.RED);
				}

				String price = ParseUtils.String2Money(goodsItem.getPrice());
				if ("0".equals(price)) {
					goodPrice.setText("赠送");
				} else {
					goodPrice.setText(Html
							.fromHtml("￥<big>" + price + "</big>"));
				}
				// 各种套餐判断
				List<OrderOptionItem> optList = goodsItem.getOptList();
				List<OrderSubGoodsItem> subGList = goodsItem.getSubGList();
				if ((null != optList && optList.size() > 0)
						|| (null != subGList && subGList.size() > 0)) { // 商品属性
					goodOption
							.setText("(" + getOpName(optList, subGList) + ")");
				} else {
					goodOption.setVisibility(View.GONE);
				}
				orderList.addView(itemView);
			}
		}

		String p = orderDetail.getpCoupon(); // 平台优惠金额
		if (!TextUtils.isEmpty(p) && !ParseUtils.subZeroAndDot(p).equals("0")) {
			pCoupon.setText(Html.fromHtml("-￥<big>"
					+ ParseUtils.subZeroAndDot(p) + "</big>"));
		} else {
			pCouponRela.setVisibility(View.GONE);
		}

		String s = orderDetail.getsCoupon(); // 店铺优惠金额
		if (!TextUtils.isEmpty(s) && !ParseUtils.subZeroAndDot(s).equals("0")) {
			sCoupon.setText(Html.fromHtml("-￥<big>"
					+ ParseUtils.subZeroAndDot(s) + "</big>"));
		} else {
			sCouponla.setVisibility(View.GONE);
		}
		allprices.setText(Html.fromHtml("￥<big>"
				+ ParseUtils.subZeroAndDot(orderDetail.getTotalPrice())
				+ "</big>"));
	}

	/**
	 * 加载配送信息
	 */
	private void infalaterDeliverInfo(OrderDetail orderDetail) {
		TextView name = (TextView) orderinfoLayout.findViewById(R.id.info_name);
		TextView sex = (TextView) orderinfoLayout.findViewById(R.id.info_sex);
		TextView phone = (TextView) orderinfoLayout
				.findViewById(R.id.info_phone);
		TextView addr = (TextView) orderinfoLayout.findViewById(R.id.info_addr);
		TextView pay = (TextView) orderinfoLayout.findViewById(R.id.info_pay);
		TextView time = (TextView) orderinfoLayout.findViewById(R.id.info_time);
		TextView remark = (TextView) orderinfoLayout
				.findViewById(R.id.info_remark);
		TextView contactshops = (TextView) orderinfoLayout
				.findViewById(R.id.info_contactshops);
		// TextView complaintshops = (TextView)
		// orderinfoLayout.findViewById(R.id.info_complaintshops);
		TextView othershops = (TextView) orderinfoLayout
				.findViewById(R.id.info_othershops);
		LinearLayout remarkLl = (LinearLayout) orderinfoLayout
				.findViewById(R.id.info_remark_ll);
		contactshops.setOnClickListener(this);
		// complaintshops.setOnClickListener(this);
		othershops.setOnClickListener(this);
		name.setText(orderDetail.getContact());
		if (orderDetail.getSex() == 2) {
			sex.setText("先生"); // 用户性别
		} else if (orderDetail.getSex() == 1) {
			sex.setText("小姐");
		} else {
			sex.setText("");
		}
		phone.setText(orderDetail.getuPhone());
		addr.setText(orderDetail.getDeliverAddr());
		if (orderDetail.getPayType() == 1) {
			pay.setText("在线支付"); // 支付类型
		} else {
			pay.setText("货到付款");
		}
		if (!TextUtils.isEmpty(orderDetail.getSelectedTime())) {
			time.setText(orderDetail.getSelectedTime()); // 送餐时段
		}

		if (!TextUtils.isEmpty(orderDetail.getRemarks())) {
			remark.setText(orderDetail.getRemarks());
		} else {
			remarkLl.setVisibility(View.GONE);
		}
	}

	/**
	 * 加载商品属性
	 * 
	 * @param optList
	 * @param subGList
	 * @return
	 */
	private String getOpName(List<OrderOptionItem> optList,
			List<OrderSubGoodsItem> subGList) {
		StringBuilder sb = new StringBuilder();
		String gName = null;
		String tempName = null;

		if (optList != null && optList.size() > 0) {
			for (OrderOptionItem opi : optList) {
				sb.append(opi.getOptName() + "+");
			}
			tempName = sb.toString();
			if (!TextUtils.isEmpty(tempName) && tempName.length() > 1) {
				gName = tempName.substring(0, tempName.length() - 1);
			}
		}

		if (subGList != null && subGList.size() > 0) {
			for (OrderSubGoodsItem sg : subGList) {
				int num = sg.getQty();
				if (num > 1) {
					sb.append(sg.getgName() + "x" + num + "+");
				} else {
					sb.append(sg.getgName() + "+");
				}
			}
		}

		tempName = sb.toString();
		if (!TextUtils.isEmpty(tempName) && tempName.length() > 1) {
			gName = tempName.substring(0, tempName.length() - 1);
		}
		return gName;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mRefReceiver != null) {
			mContext.unregisterReceiver(mRefReceiver);
		}
	}

	/**
	 * 注册广播接收
	 */
	private void registeBroadcast() {
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.woyou.ORDERDETAIL.UPDATE"); // 只有持有相同的action的接受者才能接收此广播
		mContext.registerReceiver(mRefReceiver, filter);
	}

	/**
	 * 接受推送过来刷新订单详情的广播
	 */
	BroadcastReceiver mRefReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (oId != null) {
				loadOrderDetail(oId);
			}
		}
	};

	public void showDialog(final String info) {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				SuperUI.openPullMessageDialog(OrderDetailActivity.this, info);
			}
		});
	}

	@Override
	public void onClick(View v) {
		mActController.handlOnClick(v);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void back() {
		if (oriClassName != null
				&& oriClassName.equals(IndexFragment_.class.getName())) {
			Info<Class> info = new Info<Class>();
			info.setData(IndexFragment_.class);
			openActivity(HomeActivity_.class, info);
			finish();

		} else {
			jump2MyOrderView();
		}
	}

	@Override
	public boolean backOperate() {
		// 硬件的返回键处理
		if (mOrderDetail != null) {
			Command command = BackCommandFactory.createBackCommand(
					OrderDetailActivity.this, mOrderDetail.getState());
			if (command != null) {
				command.execute();
			} else {
				back();
			}
		} else {
			jump2MyOrderView();
		}
		return true;
	}

	/** 跳转到我的订单界面 */
	private void jump2MyOrderView() {
		Info<String> info = new Info<String>();
		info.setOrigin(OrderDetailActivity.class);
		openActivity(MyOrderActivity.class, info);
		finish();
	}

	private void dismissDialog() {
		if (assessmentLayout.getVisibility() == View.VISIBLE)
			assessmentLayout.setVisibility(View.GONE);
		if (cancelLayout.getVisibility() == View.VISIBLE)
			cancelLayout.setVisibility(View.GONE);
		if (conReceivTimeOrder.getVisibility() == View.VISIBLE)
			conReceivTimeOrder.setVisibility(View.GONE);
	}

	@Override
	public void payAgain() {
		mActController.loadOrderDetailJumpPay(oId);
	}

	@Override
	public void popCommentDialog() {
		if (assessmentLayout == null)
			return;
		if (assessmentLayout.getVisibility() == View.GONE) {
			assessmentLayout.show(mOrderDetail.getsId(), mOrderDetail.getoId());

		} else {
			assessmentLayout.setVisibility(View.GONE);
		}

	}

	@Override
	public void popConfirmDialog() {
		if (conReceivTimeOrder == null)
			return;
		if (conReceivTimeOrder.getVisibility() == View.GONE) {
			conReceivTimeOrder.show(mOrderDetail.getAcceptTime(),
					mOrderDetail.getoId());

		} else {
			conReceivTimeOrder.setVisibility(View.GONE);
			conReceivTimeOrder.clear();
		}

	}

	@Override
	public void popCancelDialog() {
		if (cancelLayout == null)
			return;
		if (cancelLayout.getVisibility() == View.GONE) {
			if (mOrderDetail.getState() == State.NEW_ORDER_ONLINEPAY) {
				cancelLayout.setMassage("您的订单尚未支付,是否要取消此订单?", false);
			} else {
				cancelLayout.setMassage("已被接受的订单须征求店铺的同意才能取消", true);
			}
			cancelLayout.show(mOrderDetail.getoId());

		} else {
			cancelLayout.setVisibility(View.GONE);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onNewIntent(android.content.Intent)
	 */
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		getData();
	}

}
